package info.zlong.visibleruntime.log4j2;

import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.status.StatusLogger;
import com.alibaba.fastjson.JSON;

import info.zlong.visibleruntime.core.model.LogMsg;
import info.zlong.visibleruntime.core.mongo.MongoConnector;

@Plugin(name = "MongoDbAppender", category = "Core", elementType = "appender", printObject = true)
public class MongoDbAppender extends AbstractAppender {
	private static final Logger logger = StatusLogger.getLogger();
	private final MongoConnector mongoConnector;
	
	protected MongoDbAppender(String name, String hosts,String userName,String password, String databaseName, String collectionName) {
		super(name, null, null);
		mongoConnector = new MongoConnector(hosts,userName,password, databaseName, collectionName);
	}

	@Override
	public void start() {
		mongoConnector.open();
		super.start();
	}
	
	@Override
	public boolean stop(long timeout, TimeUnit timeUnit) {
		mongoConnector.close();
		return super.stop(timeout, timeUnit);
	}

    @PluginFactory
    public static MongoDbAppender createAppender(
            @PluginAttribute("name") final String name,
            @PluginAttribute("hosts") final String hosts,
            @PluginAttribute("userName") final String userName,
            @PluginAttribute(value = "password", sensitive = true) final String password,
            @PluginAttribute("databaseName") final String databaseName,
            @PluginAttribute("collectionName") final String collectionName) {
        if (hosts == null) {
            LOGGER.error("没有hosts for appender [{}].", name);
            return null;
        }

        if (databaseName == null) {
            LOGGER.error("没有databaseName for appender [{}].", name);
            return null;
        }

        if (collectionName == null) {
            LOGGER.error("没有collectionName for appender [{}].", name);
            return null;
        }

        return new MongoDbAppender(name, hosts,userName,password, databaseName, collectionName);
    }


	public void append(LogEvent event) {
		String msg = event.getMessage().getFormattedMessage();
		try{
		LogMsg logMsg = JSON.parseObject(msg, LogMsg.class);
		mongoConnector.update(logMsg);
		}catch (Exception e) {
			logger.error("LogMsg存入Mongo出错:"+msg,e);
		}
	}
}
